package com.sunxiansheng.designPattern.factoryandstragy;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: 获取策略对象的工厂
 * @Author sun
 * @Create 2024/7/22 11:07
 * @Version 1.0
 */
@Component
public class PayFactory implements InitializingBean {

    /**
     * 所有的具体支付策略的对象逻辑会被注入到这里
     */
    @Resource
    private List<PayHandler> payHandlerList;

    /**
     * 存储策略标识和具体策略的map
     */
    private Map<PayChannelEnum, PayHandler> handlerMap = new HashMap<>();

    /**
     * 根据枚举的code来获取对应的策略
     * @param code
     * @return
     */
    public PayHandler getHandlerByCode(int code) {
        PayChannelEnum byCode = PayChannelEnum.getByCode(code);
        return handlerMap.get(byCode);
    }

    /**
     * 在bean初始化之后，这个方法会被调用
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        // 将所有的策略从list放到map中，直接通过枚举即可获得对应的策略
        for (PayHandler payHandler : payHandlerList) {
            handlerMap.put(payHandler.getChannel(), payHandler);
        }
    }

}